/*MyPhotoIndex Free Photo Organizer <www.myphotoindex.com>
  Copyright (C) <2006-2007>  <Asaf Yarkoni asaf@yarkoni.net>

  This program is free software: you can redistribute it and/or modify
  it under the terms of the GNU General Public License as published by
  the Free Software Foundation, either version 3 of the License, or
  (at your option) any later version.

  This program is distributed in the hope that it will be useful,
  but WITHOUT ANY WARRANTY; without even the implied warranty of
  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
  GNU General Public License for more details.

  You should have received a copy of the GNU General Public License
  along with this program.  If not, see <http://www.gnu.org/licenses/>.*/
using System;
using System.Collections.Generic;
using System.Text;
using System.Net;
using System.Globalization;
using System.Security.Cryptography;
using System.IO;
using System.Xml.Serialization;
using System.Xml;
using System.Windows.Forms;
using MyPhotoIndex.Utilities;

namespace MyPhotoIndex.Plugins.Share.Facebook.Fb_API
{

    public class Authentication
    {
        private const string FACEBOOK_HTTP_URI = "http://api.facebook.com/bestserver.php";
        private const string FACEBOOK_HTTPS_URI = "https://api.facebook.com/bestserver.php";
        private const string LOGIN_URL_FORMAT = @"http://www.facebook.com/login.php?api_key={0}&v=1.0&auth_token={1}&popup=true";
        //http://www.facebook.com/authorize.php?api_key=650b150054e483ccb33c51844fdeb4ac&v=1.0&ext_perm=photo_upload
        private CookieCollection    m_cookies = new CookieCollection();
        private String              m_authToken;
        private String              m_apiKey;
        private String              m_secret;
        private String              m_sessionKey;

        internal String SessionKey
        {
            get { return m_sessionKey; }
            set { m_sessionKey = value; }
        }

        internal String ApiKey
        {
            get { return m_apiKey; }
            set { m_apiKey = value; }
        }

        internal String Secret
        {
            get { return m_secret; }
            set { m_secret = value; }
        }

        public bool SignIn(String appKey, String secret)
        {
            m_apiKey = appKey;
            m_secret = secret;

            try
            {
                HttpWebRequest request = HttpWebRequest.Create(FACEBOOK_HTTP_URI) as HttpWebRequest;
                RequestBuilder requestBuilder = new RequestBuilder(appKey, secret);
                requestBuilder.InitializeRequest(request, "auth.createToken", String.Empty, false);

                String responseData = String.Empty;
                WebResponse response = request.GetResponse();
                using (Stream responseStream = response.GetResponseStream())
                {
                    StreamReader reader = new StreamReader(responseStream);
                    responseData = reader.ReadToEnd();
                }

                XmlSerializer serializer = new XmlSerializer(typeof(auth_createToken_response));
                auth_createToken_response authToken = (auth_createToken_response)serializer.Deserialize(new StringReader(responseData));
                m_authToken = authToken.Token;

                String url = String.Format(LOGIN_URL_FORMAT, appKey, m_authToken);
                Browser browser = new Browser(url);
                DialogResult dr = browser.ShowDialog();
                if (dr == DialogResult.Cancel)
                {
                    return false;
                }

                HttpWebRequest sessionRequest = HttpWebRequest.Create(FACEBOOK_HTTPS_URI) as HttpWebRequest;
                RequestBuilder sessionRequestBuilder = new RequestBuilder(appKey, secret);
                sessionRequestBuilder.Add("auth_token", m_authToken);
                sessionRequestBuilder.InitializeRequest(sessionRequest, "auth.getSession", String.Empty, false);

                response = sessionRequest.GetResponse();
                using (Stream responseStream = response.GetResponseStream())
                {
                    StreamReader reader = new StreamReader(responseStream);
                    responseData = reader.ReadToEnd();
                }

                serializer = new XmlSerializer(typeof(auth_getSession_response));
                auth_getSession_response sessionResponse = (auth_getSession_response)serializer.Deserialize(new StringReader(responseData));

                m_sessionKey = sessionResponse.session_key;
                m_secret = sessionResponse.secret;

            }
            catch (Exception ex)
            {
                Logger.Log(ex);
                return false;
            }

            return true;
        }

        public String AuthToken
        {
            get { return m_authToken; }
            set { m_authToken = value; }
        }
      
    }
}
